package team.future.joke.service.impl;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import team.future.joke.constant.WeixinConstants;
import team.future.joke.controller.WeixinUtil;
import team.future.joke.dao.BaseMongoDao;
import team.future.joke.entity.WeixinConfig;
import team.future.joke.service.WeixinService;
/**
 * Title: WeixinServiceImpl.java<br>
 * Description: <br>
 * Copyright (c) 未来工作室版权所有 2015    <br>
 * Create DateTime: 2015年9月21日 下午6:45:40 <br>
 * @author futurezhu
*/
@Service("weixinService")
public class WeixinServiceImpl implements WeixinService {

	@Autowired
	private BaseMongoDao<WeixinConfig> weixinDao;

	@Override
	public WeixinConfig getWeixinConfig() {
		WeixinConfig config = weixinDao.getObject(query(where("appId").is(WeixinConstants.APPID)));
		if (config == null) {
			config = new WeixinConfig();
			//获取token
			String token = WeixinUtil.getToken();
			//根据算法获取签名
			String timeStamp = WeixinUtil.getTimeStamp();
			String signature = WeixinUtil.getSignature(token, timeStamp);
			if (StringUtils.isEmpty(signature)) {
				throw new RuntimeException("生成签名失败");
			}
			config.setSignature(signature);
			config.setToken(token);
			config.setTimestamp(timeStamp);
			weixinDao.insertObject(config);
		}
		return config;
	}

	@Override
	public void updateWeixinConfig() {
		WeixinConfig config = weixinDao.getObject(query(where("appId").is(WeixinConstants.APPID)));
		if (config == null) {
			config = new WeixinConfig();
			//获取token
			String token = WeixinUtil.getToken();
			//根据算法获取签名
			String timeStamp = WeixinUtil.getTimeStamp();
			String signature = WeixinUtil.getSignature(token, timeStamp);
			if (StringUtils.isEmpty(signature)) {
				throw new RuntimeException("生成签名失败");
			}
			config.setSignature(signature);
			config.setToken(token);
			config.setTimestamp(timeStamp);
			weixinDao.insertObject(config);
		} else {
			//获取token
			String token = WeixinUtil.getToken();
			//根据算法获取签名
			String timeStamp = WeixinUtil.getTimeStamp();
			String signature = WeixinUtil.getSignature(token, timeStamp);
			if (StringUtils.isEmpty(signature)) {
				throw new RuntimeException("生成签名失败");
			}
			config.setSignature(signature);
			config.setToken(token);
			config.setTimestamp(timeStamp);
			weixinDao.deleteObject(query(where("appId").is(WeixinConstants.APPID)));
			weixinDao.insertObject(config);
		}
	}

}
